
#include "MRadar.h"
#include <GL\GL.h>
CTexture _texture;
MRadar::MRadar(int x, int y, int w, int h)
{
	_x = x;
	_y = y;
	_w = w;
	_h = h;
	
	_texture = new CTexture();
	_texture->LoadTexture(MEDIA_DIR "ground.tga");

	glGenTextures(1, &_texture->texID);
	glBindTexture(GL_TEXTURE_2D, _texture->texID);
	
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, _texture->width, _texture->height, GL_RGB, GL_UNSIGNED_BYTE, _texture->data);
}

MRadar::~MRadar()
{
	delete _texture;
}

double MRadar::pointDistance(float x, float y, float x2, float y2)
{
	return std::sqrt(std::pow(x - x2, 2) + std::pow(y - y2, 2));
}

void MRadar::Render(CPlayer *p, std::vector<CEnemy*> enemies, CCamera *cam, float worldDistanceClose, float worldDistanceFar)
{
	float tx = 0.0;
	float tx2 = 1.0;
	float ty = 0.0;
	float ty2 = 1.0f;
	float worldRadarWidth = 0.1;
	float distanceRatio = worldDistanceClose/worldDistanceFar;

	// Clamp world teture data
	if(tx < 0)
	{
		tx = 0;
	}

	if(tx > 1 - worldRadarWidth)
	{
		tx = 1 - worldRadarWidth;
	}

	glDepthMask(GL_FALSE);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, _texture->texID);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
	glBegin(GL_QUADS);
		glTexCoord2f(tx, ty);
		glVertex2i(_x, _y);
		glTexCoord2f(tx, ty2);
		glVertex2i(_x, _y + _h);
		glTexCoord2f(tx2, ty2);
		glVertex2i(_x + _w, _y + _h);
		glTexCoord2f(tx2, ty);
		glVertex2i(_x + _w, _y);
	glEnd();

	glColor3f(0.0f, 0.0f, 0.0f);
	glBegin(GL_LINE_LOOP);
		glVertex2i(_x, _y);
		glVertex2i(_x, _y + _h);
		glVertex2i(_x + _w, _y + _h);
		glVertex2i(_x + _w, _y);
	glEnd();

	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);
	glDepthMask(GL_TRUE);
	
	glPushMatrix();
	glLoadIdentity();

	float halfWidth = (float)_w/2;
	glTranslatef(_x + halfWidth, _y + halfWidth, 0.0f);
	
	glRotatef(-cam->yaw + 90, 0.0f, 0.0f, 1.0f);

	glPointSize(5);
	glColor3f(1.0f, 0.1f, 0.1f);
	glBegin(GL_POINTS);
		for(unsigned i = 0; i < enemies.size(); i++)
		{
			float enemyX = enemies[i]->position.x;
			float enemyY = enemies[i]->position.z;
			float pX = (cam->position.x - enemyX) * distanceRatio;
			float pY = (cam->position.z - enemyY) * distanceRatio;
			float pointX = (pX * halfWidth);
			float pointY = (pY * halfWidth);

			if(this->pointDistance(0, 0, pointX, pointY) <= halfWidth)
			{
				glVertex2f(pointX, pointY);
			}
		}
		
		glPointSize(8);
		glColor3f(0.0f, 1.0f, 0.0f);
		glVertex2f(0.0f, 0.0f);
	glEnd();

	glPopMatrix();
}